<?php
namespace app\home\controller;

//引入Thinkphp控制器基类
use app\common\controller\Home;


//在模板中如何进行跳转？使用框架的函数
//在模板中输出的基本格式：{}

class Index extends Home
{   
    public $NoLogin = ['*'];  

    public function __construct()
    {   
        //继承父类的构造函数
        parent::__construct();
        //加载模型
        $this -> BusinessModel = model('Business.Business');
        $this -> SubjectModel  = model('common/Subject/Subject');
        $this -> TeacherModel  = model('common/Teacher/Teacher');
        $this -> CategoryModel = model('Subject.Category');
    }
    //首页
    public function index()
    {   
        $top = $this ->SubjectModel -> group('cateid') ->order('id','desc')->limit(6)->select();

        $subject = $this ->SubjectModel -> order('id','desc')->limit(10)->select();

        $teacher = $this -> TeacherModel -> limit(10) ->select();


        $this -> assign([
            'top' => $top,
            'subject' => $subject,
            'teacher' => $teacher
        ]);

        //给当前控制器指向一个模板视图(页面)
        //若fetch()中没有给出具体模板视图名称
        //则也会有一套自己的命名规则
        // view/控制器文件夹名/方法名.html
        // view/index/index.html
        return  $this->view->fetch();
        
        // $username = 'hello worlld';

        // $list= [
        //     ['nickname' =>'张三','age'=> 20,'sex'=> '男'],
        //     ['nickname' =>'张三','age'=> 20,'sex'=> '男'],
        //     ['nickname' =>'张三','age'=> 20,'sex'=> '男'],
        //     ['nickname' =>'张三','age'=> 20,'sex'=> '男'],
        //     ['nickname' =>'张三','age'=> 20,'sex'=> '男'],
        // ];

        //将数据传递到视图模板
        //assgin(为想要显示的变量取名，对应的实际变量名)
        // $this->view->assign('username',$username);
        // $this->view->assign('list',$list);


        
    }

    //注册
    public function register()
    {   
        //判断是否有推荐人的token参数
        $token = $this->request->param('token','','trim');

        if(!empty($token))
        {
            //模仿加密方式，找出token对应的用户
            $list = $this->BusinessModel->field(['id','mobile'])->select();

            if($list)
            {
                foreach($list as $item)
                {
                    //加密
                    $value = md5($item['id'].$item['mobile']);

                    //将每个循环加密后的value与传过来的token比较
                    //如果相等，则说明找到了对应的用户
                    if($value == $token)
                    {
                        //就将推广人存入到cookie中,找到对应用户后break出循环
                        cookie('token',$token);
                        break;
                    }
                }
            }
            
        }
        //判断是否有POST请求传入
        if($this->request->isPost())
        {
            $mobile = $this->request->param('mobile','','trim');
            $password  = $this->request->param('password','','trim');  
            
            if(empty($password))
            {
                $this -> error('密码不能为空！');
                exit;
            }

            //生成密码盐
            $salt = randstr(10);      //application/common.php

            //加密密码
            $repass = md5($password. $salt);

            //查询注册的来源渠道,加载模型 会自动的去找模型(路径)：application/common/Business/Source
            $sourceid = model('Business.Source')->where(['name' => ['LIKE','%云课堂%']]) ->value('id');

            //模型SQL语句打印方法
            // $sql = model('Business.Source')->where(['name' => ['LIKE','%云课堂%']])->getLastSql();
            // echo $sql;
            // exit;

            
            //组装数据
            $data = [
                'mobile' => $mobile,
                'nickname'=> build_encrypt($mobile,3,4),    //脱敏显示
                'salt'   => $salt,
                'password' => $repass,
                'sourceid' => $sourceid,
                'gender' => '0',
                'deal'   => '0',
                'money'  => '0',
                'auth'   => '0',
            ];

            //判断是否存在token
            //判断是否有推荐人的token参数
            $token = $this->request->param('token','','trim');
            
            $token = empty($token) ? cookie('token'): $token;


            if(!empty($token))
            {
                //模仿加密方式，找出token对应的用户
                $list = $this->BusinessModel->field(['id','mobile'])->select();

                if($list)
                {
                foreach($list as $item)
                {
                    //加密
                    $value = md5($item['id'].$item['mobile']);

                    //将每个循环加密后的value与传过来的token比较
                    //如果相等，则说明找到了对应的用户
                    if($value == $token)
                    {
                        //将推荐人的id保留下来,parentid字段即为推荐人id字段
                        $data['parentid'] = $item['id'];
                        break;
                    }
                }
            }            
        }

            //插入数据
            //validate() 验证器 成功返回插入的条数 失败返回false
            $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

            if($result === FALSE)
            {
                //插入失败  让模型来返回错误信息
                $this -> error($this->BusinessModel->getError());
                exit;
            }else
            {
                $this->success('注册成功，请登录',url('/home/index/login'));
                exit;
            }
        }
        //此方法会找的默认路径为：view/index/register.html
        //访问地址:www.fast.com/index.php/home/index/register
        return $this->view->fetch();
    }

    //登录
    public function login()
    {   
        //判断是否有POST请求传入
        if($this->request->isPost())
        {
            $mobile = $this->request->param('mobile','','trim');
            $password = $this->request->param('password','','trim');

            //查询用户是否存在
            $business = $this->BusinessModel->where(['mobile'=>$mobile])->find();

            if(empty($business))
            {
                $this->error('用户不存在');
                exit;
            }

            // 查询一条数据 一维数组
            // $business = model('Business.Business')->where(['mobile'=> $mobile])->find();

            // 将模型数据转换成数组
            // var_dump($business->toArray());

            // 查询多条数据 二维数组
            // $business = model('Business.Business')->where(['mobile'=> $mobile])->select();

            // 将集合转换成数组
            // var_dump($business->toArray());

            //验证密码是否正确
            // var_dump($business->toArray());
            // exit;   

            //验证密码是否正确
            $salt = $business['salt'];
            $repass = md5($password.$salt);

            if($repass != $business['password'])
            {
                $this->error('密码错误');
                exit;
            }

            //存入手机号码和ID的cookie
            cookie('mobile',$business['mobile']);
            cookie('busid',$business['id']);

            //获取是否有登录后的跳转界面
            $redirect = cookie('redirect');

            if($redirect)
            {
                $this -> success('登录成功',$redirect);
                exit;
            }else
            {
                $this->success('登录成功',url('home/business/index'));
                exit; 
            }              
        }


        //访问地址:www.fast.com/index.php/home/index/login
        //此方法会找的默认路径为: view/index/login.html
        return $this->view->fetch();

        
    }

    //退出
    public function logout()
    {   

        //判断是否是Ajax请求
        if($this->request->isAjax())
        {
            //删除掉cookie信息
            cookie('busid',NULL);
            cookie('mobile',NULL);

            //由于是Ajax请求，则判断结果后不会返回上一界面
            //而是会根据语境返回json的结果
            $this->success('退出成功');
            exit;
        }else
        {
            $this->error('退出失败');
            exit;
        }
    }
}